package 二叉树;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
 */
public class _144_二叉树的前序遍历 {
    List<Integer> list = new ArrayList<>();

    /**
     * 递归前序遍历
     *
     * @param root
     * @return
     */
    public List<Integer> preorderTraversal(TreeNode root) {
        if (root == null) return list;

        list.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return list;
    }

    /**
     * 迭代最优版
     */
    public List<Integer> preorderTraversal2(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode node = root;
        while (true) {
            if (node != null) {
                list.add(node.val);
                if (node.right != null) stack.push(node.right);
                node = node.left;
            } else if (stack.isEmpty()) {
                break;
            } else {
                node = stack.pop();
            }

        }
        return list;
    }

    /**
     * 迭代
     *
     * @param root
     * @return
     */
    List<Integer> list1 = new ArrayList<>();

    public List<Integer> preorderTraversal1(TreeNode root) {
        if (root == null) return list1;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.add(node.val);
            //先进后出
            // 根左右
            if (node.right != null) stack.push(node.right);
            if (node.left != null) stack.push(node.left);

        }
        return list1;
    }
}
